// 文件上传（单文件上传）
<template>
  <div class="file-upload" @mouseenter="handleHover" @mouseleave="handleHover('leave')">
    <div :class="['upload-wrap',{'w100':logoCss}]">
      <div v-if="hover&&(canShow||fileShow)" class="review">
        <div>{{ title }}</div>
        <div class="btn-group">
          <span v-if="canShow" title="预览" @click="reviewItem()">
            <i class="el-icon-view" />
          </span>
          <span v-if="fileShow">
            <a :href="form[photoName]" type="download" :download="'文件-'+new Date()" target="_blank" title="查看下载">
              <i class="el-icon-download" />
            </a>
          </span>
          <span v-if="!noDeleteBtn" title="删除" @click="removeItem(form[photoName])">
            <i class="el-icon-delete" />
          </span>
          <span v-if="importFlag" title="导入" @click="importFun(form[photoName])">
            <i class="el-icon-thumb" />
          </span>
        </div>
      </div>

      <!-- 上传文件 -->
      <input ref="uploadInput" class="input" :title="title" type="file" @change="handleChange($event,this)">
      <el-progress v-if="upload" class="progress" type="circle" :percentage="progress" />
      <!-- 图片回显 -->
      <div
        v-if="isImg(form[photoName]) && fileType==='img'"
        :style="{'background':'url('+$store.state.user.ftpInfo.checkOn+'/'+form[photoName]+')'}"
        class="img-wrap img-view"
      />
      <!-- 视频回显 -->
      <video
        v-if="form[photoName] && fileType==='video'"
        :src="$store.state.user.ftpInfo.checkOn+'/'+form[photoName]"
        class="video-wrap"
      />
      <!-- 文件回显 -->
      <div v-if="isFile(form[photoName]) && fileType==='file'" class="file-review">
        <svg-icon
          class="file"
          style="width:80px; height:80px; margin-top:20px; position:absolute;left:50%;margin-left:-40px;z-index:1;"
          class-name="international-icon"
          icon-class="sign_files"
        />
      </div>
      <i v-else class="el-icon-plus uploader-icon" />
      <div class="title">{{ title }}</div>
    </div>
    <!-- 图片视频弹出 -->
    <el-dialog :title="title" :visible.sync="dialogStatus" width="40%" top="10vh" :append-to-body="true">
      <img
        v-if="form[photoName] && fileType==='img'"
        style="width:100%"
        :src="$store.state.user.ftpInfo.checkOn+'/'+form[photoName]"
        class="img-wrap"
      >
      <video
        v-if="form[photoName] && fileType==='video'"
        style="width:100%;height: 75vh;"
        controls
        :src="$store.state.user.ftpInfo.checkOn+'/'+form[photoName]"
        class="video-wrap"
      />
      <span slot="footer">
        <el-button size="mini" @click="dialogStatus = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// TODO: 文件Word，Excel，PDF上传
import { mapState } from 'vuex'
import { filetoftp } from '@/api/filetoftp/filetoftp'
export default {
  props: {
    form: Object, // 上传的对应表单名称
    photoName: String, // 上传的对应字段名称
    title: String, // 标题
    noDeleteBtn: Boolean, // true为没有删除按钮
    logoCss: Boolean, // 样式
    importFlag: Boolean, // 导入标记
    duration: Number, // 时长
    removeFlag: Boolean,
    type: null
  },
  data() {
    return {
      folderName: 'other', // 文件夹命上传路径 工人 custemer 雇主 employer 中介 agent 默认 other
      upload: false,
      progress: 0,
      dialogStatus: false,
      hover: false,
      canShow: false,
      fileShow: false,
      fileType: 'img',
      demo: 0
    }
  },
  computed: {
    isImg() {
      // 判断是图片
      return function(val) {
        if (val) {
          const miniTpye = val.split('.')[val.split('.').length - 1]

          if (
            miniTpye === 'jpeg' ||
              miniTpye === 'jpg' ||
              miniTpye === 'png' ||
              miniTpye === 'GIF' ||
              miniTpye === 'JPG' ||
              miniTpye === 'PNG' ||
              miniTpye === 'gif'
          ) {
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.fileType = 'img'
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.canShow = true
            return true
          } else if (miniTpye === 'mp4') {
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.fileType = 'video'
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.canShow = true
            return true
          } else {
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.canShow = false
            return false
          }
        } else {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.canShow = false
          return false
        }
      }
    },
    isFile() {
      // 判断是文件
      return function(val) {
        if (val) {
          const fileType = val.split('.')[val.split('.').length - 1]
          if (
            fileType === 'pdf' ||
              fileType === 'xls' ||
              fileType === 'ppt' ||
              fileType === 'pptx' ||
              fileType === 'xlsx' ||
              fileType === 'doc' ||
              fileType === 'docx' ||
              fileType === 'zip' ||
              fileType === 'PDF' ||
              fileType === 'sql' ||
              fileType === 'html' ||
              fileType === 'json' ||
              fileType === 'jar' ||
              fileType === 'js' ||
              fileType === 'rar' ||
              fileType === 'txt'
          ) {
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.fileType = 'file'
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.fileShow = true
            return true
          } else {
            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.fileShow = false
            return false
          }
        } else {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.fileShow = false
          return false
        }
      }
    },
    ...mapState({
      switchConfig: state => state.whole.switchConfig
    })
  },
  filters: {
    filterType(type) {
      if (
        type === 'jpg' ||
          type === 'jpeg' ||
          type === 'png' ||
          type === 'GIF' ||
          type === 'JPG' ||
          type === 'PNG' ||
          type === 'gif'
      ) {
        return 'img'
      }
      if (type === 'mp4') {
        return 'video'
      }
      if (
        type === 'docx' ||
          type === 'doc' ||
          type === 'pptx' ||
          type === 'ppt' ||
          type === 'xlsx' ||
          type === 'xls' ||
          type === 'pdf' ||
          type === 'PDF' ||
          type === 'zip' ||
          type === 'sql' ||
          type === 'html' ||
          type === 'json' ||
          type === 'jar' ||
          type === 'js' ||
          type === 'rar' ||
          type === 'txt'
      ) {
        return 'file'
      }
    }
  },
  watch: {
    demo(r, e) {
      this.$emit('handleChang', Number(r))
    }
  },
  methods: {
    handleChange(file, el) {
      // console.log(file,el)
      const uploadFile = file.target.files[0]
      // const fileSize = uploadFile.size / 1024 / 1024
      const fileName = file.target.files[0].name
      this.$emit('handleChang', { fileName: fileName })
      const fileExtendName = fileName.split('.')[
        fileName.split('.').length - 1
      ]
      const filter = this.$options.filters['filterType']
      this.fileType = filter(fileExtendName)
      if (uploadFile) {
        if (
          !/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName) &&
            this.fileType === 'img'
        ) {
          this.$message({
            message:
                '上传的文件类型不正确！可为（ gif | jpg | jpeg | png | GIF | JPG | PNG）文件',
            type: 'error',
            showClose: true
          })
          this.$refs.uploadInput.value = ''
          return false
        }
        if (
          !/\.(docx|doc|pptx|ppt|xlsx|xls|pdf|PDF|zip|sql|html|json|jar|js|rar|txt)$/.test(fileName) &&
            this.fileType === 'file'
        ) {
          this.$message({
            message:
                '上传的文件类型不正确！可为（ docx|doc|pptx|ppt|xlsx|xls|pdf|PDF|zip|sql|html|json|jar|js|rar|txt ）文件',
            type: 'error',
            showClose: true
          })
          this.$refs.uploadInput.value = ''
          return false
        }
        if (this.type === 'video') {
          // if (!/\.(mp4)$/.test(fileName)  ) {
          if ((fileName.split('.')[1]).toLowerCase() !== 'mp4' && (fileName.split('.')[1]).toLowerCase() !== 'ogg' && (fileName.split('.')[1]).toLowerCase() !== 'swf') {
            this.$message({
              message: '上传的文件类型不正确！只能上传MP4、ogg或者swf视频文件',
              type: 'error',
              showClose: true
            })
            this.$refs.uploadInput.value = ''
            return false
          }
        }

        if (/\.(mp4)$/.test(fileName) && this.fileType === 'video') {
          var url = URL.createObjectURL(file.target.files[0])
          // 经测试，发现audio也可获取视频的时长
          var audioElement = new Audio(url)
          // var duration
          var self = this
          // let promise = new Promise(function (res, rej) {
          //   res()

          // });
          // promise.then(function () {
          //   audioElement.addEventListener("loadedmetadata", function (_event) {
          //     self.demo = audioElement.duration;
          //   });

          // }).then(function(){
          //   console.log(self.demo);
          // })
          audioElement.addEventListener('loadedmetadata', function(_event) {
            self.demo = audioElement.duration
          })
          // this.demo = duration
          // console.log(duration);
          // this.duration = duration
        }
        const formData = new FormData()
        formData.append('file', uploadFile)
        // var config = {
        //   onUploadProgress: progressEvent => {
        //     this.upload = true
        //     var complete =
        //         ((progressEvent.loaded / progressEvent.total) * 100) | 0
        //     this.progress = complete
        //   }
        // }

        filetoftp(uploadFile).then(res => {
          setTimeout(() => {
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            this.form[this.photoName] = res.files[0].path
            this.$refs.uploadInput.value = ''
          }, 1000)
        })
      }
    },
    removeItem(item) {
      this.demo = 0
      this.$refs.uploadInput.value = '' // 清除value可以进行二次上传
      this.form[this.photoName] = null
      if (this.removeFlag) {
        this.$emit('listenUpload', { photoName: this.photoName, ossUrl: '' })
      }
    },
    reviewItem(item) {
      this.dialogStatus = true
    },
    handleHover(type) {
      // 鼠标经过事件 显示预览和删除按钮
      if (type === 'leave') {
        this.hover = false
      } else {
        this.hover = true
      }
    },
    // 图片导入
    importFun(val) {
      this.$emit('importImgFun', { photoName: this.photoName, path: val })
    }
  }
}
</script>

<style scoped lang="scss">
  .file-upload {
    display: inline-block;

    .title {
      text-align: center;
      width: 120px;
      bottom: 15px;
      position: absolute;
      width: 100%;
      left: 0;
    }

    transition: all 0.5s ease-in-out;
  }

  /*
.file-upload:hover {
  .upload-wrap {
    border-color: $mainColor;
  }
} */

  .review {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 102;
    background-color: rgba(0, 0, 0, 0.55);
    color: #fff;
    /* @include flex(column, space-evenly, center); */

    transition: all 0.5s ease-in-out;
    animation: fadeIn 0.5s ease-in-out;

    span {
      cursor: pointer;
    }

    span:first-child {
      /* padding-right: 15px; */

      i {
        font-size: 16px;
      }
    }
  }

  .img-view {
    background-repeat: no-repeat !important;
    background-size: cover !important;
    background-position: center !important;
  }

  .upload-wrap {
    width: 120px;
    height: 120px;
    position: relative;
    border-radius: 5px;
    overflow: hidden;
    border: 1px dashed #dcdcdc;
    background-color: #f5f4f7;
    transition: all 0.5s ease-in-out;

    .input,
    .progress,
    .img-wrap,
    .video-wrap,
    .uploader-icon {
      position: absolute;
      z-index: 99;
      width: 100%;
      height: 100%;
    }

    .uploader-icon {
      font-size: 24px;
      text-align: center;
      line-height: 110px;
      color: #666;
      z-index: 2;
    }

    .input {
      opacity: 0;
      cursor: pointer;
    }

    .progress {
      z-index: 100;
      width: 110px;
      height: 100px;
      left: 5px;
      top: 5px;
      background-color: #f5f4f7;

      /deep/ .el-progress-circle {
        width: 100% !important;
        height: 100% !important;
      }
    }

    .img-wrap,
    .video-wrap {
      background-color: #000;
      z-index: 98;
    }

    .file-review {
      display: block;
      font-size: 36px;
      text-align: center;
      line-height: 100px;
    }
  }
  .review>div{
    height: 50%;
  }
  .w100 {
    width: 100px;
    height: 100px;
    border: 1px solid #ddd;
    border-radius: 50%;
  }

  .btn-group,
  .review>div:nth-of-type(1) {
    text-align: center;
  }
  btn-group{
    display: flex;
    flex-direction: row;
    justify-content: space-around;
  }
  .review>div:nth-of-type(1) {}
</style>
